package com.tedu.myblog.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tedu.myblog.entity.Picture;
import com.tedu.myblog.service.PictureService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

//照片墙后台管理

@Controller
@RequestMapping("/admin")
public class PictureController {

    @Autowired
    private PictureService pictureService;

//    查询照片列表
    @GetMapping("/pictures")
    public String pictures(Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum,3);
        List<Picture> listFriendLink = pictureService.listPicture();
        for (Picture picture : listFriendLink) {
			System.out.println("-------------------"+picture.getPictureaddress()+"---------------------");
			
		}
        PageInfo<Picture> pageInfo = new PageInfo<Picture>(listFriendLink);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/pictures";
    }

//    跳转新增页面
    @GetMapping("/pictures/input")
    public String input(Model model) {
        model.addAttribute("picture", new Picture());
        return "admin/pictures-input";
    }

//    照片新增
    @PostMapping("/pictures")
    public String post(@Valid Picture picture, Model model, BindingResult result, RedirectAttributes attributes,MultipartFile file){

        if(result.hasErrors()){
            return "admin/pictures-input";
        }
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://pictures//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/pictures/" + fileName;
        System.out.println("`````````````````"+filename+"```````````````````````");
        picture.setPictureaddress(filename);
        
        int P = pictureService.savePicture(picture);
        if (P == 0 ) {
            attributes.addFlashAttribute("message", "新增失败");
        } else {
            attributes.addFlashAttribute("message", "新增成功");
        }
        return "redirect:/admin/pictures";
    }

//    跳转照片编辑页面
    @GetMapping("/pictures/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        model.addAttribute("picture", pictureService.getPicture(id));
        return "admin/pictures-input";
    }

//    编辑相册
    @PostMapping("/pictures/{id}")
    public String editPost(@Valid Picture picture, RedirectAttributes attributes,MultipartFile file) {
    	if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://pictures//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/pictures/" + fileName;
        System.out.println("`````````````````"+filename+"```````````````````````");
        picture.setPictureaddress(filename);
    	
    	System.out.println("===================="+picture.getPictureaddress()+"==============================");
    	System.out.println("===================="+picture.getId()+"==============================");
    	Picture picture2 = pictureService.getPicture(picture.getId());
    	System.out.println("===================="+picture2.getPictureaddress()+"==============================");
    	File f = new File("d://"+picture2.getPictureaddress());
    	f.delete();
        int P = pictureService.updatePicture(picture);
        System.out.println("==========================="+P+"=====================================");
        if (P == 0 ) {
            attributes.addFlashAttribute("message", "编辑失败");
        } else {
            attributes.addFlashAttribute("message", "编辑成功");
        }
        return "redirect:/admin/pictures";
    }

//    删除照片
    @GetMapping("/pictures/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes){
    	
    	Picture picture2 = pictureService.getPicture(id);
    	System.out.println("========================="+picture2.getPictureaddress()+"======================");
    	
    	File f = new File("d://"+picture2.getPictureaddress());
    	f.delete();
    	
        pictureService.deletePicture(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/pictures";
    }
}